import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'
import Base64 from 'base64-js'
import { decrypt } from './rsa-decrypt.js'
import { app_public_key,app_iv,app_password_key,app_password_iv } from '../../config/config.js'

/* RSA加密
text：需要加密的内容
publicKey：加密公钥
 */
function encryptRSA(text, publicKey) {
	//rsa加密对象
	const encryptor = new JSEncrypt()
	//设置公钥
	encryptor.setPublicKey(publicKey)
	const encryptRes = encryptor.encrypt(text)
	return encryptRes
}
/* RSA解密
text：需要解密的密文
publicKey：解密公钥
 */
function decryptRSA(text, publicKey) {
	//rsa加密对象
	const decrypt = new JSEncrypt()
	//设置公钥
	decrypt.setPublicKey(publicKey)
	const decryptRes = decrypt.decrypt(text)
	return decryptRes
}
/* 接口请求参数加密 */
function networkEncrypt(text) {
	//16位随机key
	const randomKey = createPasswordKey(16)
	//对随机数进行rsa加密生成AES加密密钥
	const aesKey = encryptRSA(randomKey, app_public_key())
	//获取加密内容的WordArray
	const contentBytes = CryptoJS.enc.Utf8.parse(text)
	//获取aes加密密钥的WordArray
	const keyBytes = CryptoJS.enc.Utf8.parse(randomKey)
	//获取iv的WordArray
	const ivBytes = CryptoJS.enc.Base64.parse(app_iv())
	const encrypted = CryptoJS.AES.encrypt(contentBytes, keyBytes, {
		iv: ivBytes,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	})
	//报文aes加密结果base64
	const contentAesRes = encrypted.ciphertext.toString(CryptoJS.enc.Base64)
	const keyArr = Base64.toByteArray(aesKey)
	const contentArr = Base64.toByteArray(contentAesRes)
	const result = Base64.fromByteArray([...keyArr, ...contentArr])
	//返回加密结果base64字符串
	return result
}

/* 接口请求结果解密 */
function networkDecrypt(text = '') {
	//base64解密内容字符串转byte数组
	const datas = Base64.toByteArray(text)
	if(datas.length < 256){
		return ''
	}
	//获取aes加密密钥部分byte数组
	const keyBytes = datas.slice(0, 256)
	//获取加密密钥的base64字符串
	const keyBase64 = Base64.fromByteArray(keyBytes)
	//获取内容部分byte数组
	const contentBytes = datas.slice(256)
	//获取内容部分base64字符串
	const contentBase64 = Base64.fromByteArray(contentBytes)
	const rsaRes = decrypt(keyBase64, app_public_key())
	if (!rsaRes) {
		console.log('decrypt fail')
		return ''
	}
	///AES解密
	const aesKeyWordArray = CryptoJS.enc.Utf8.parse(rsaRes)
	const ivWordArray = CryptoJS.enc.Base64.parse(app_iv())
	const contentWordArray = CryptoJS.enc.Base64.parse(contentBase64)
	const encrypted = CryptoJS.AES.decrypt({
		ciphertext: contentWordArray
	}, aesKeyWordArray, {
		iv: ivWordArray,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7,
	});
	const res = CryptoJS.enc.Utf8.stringify(encrypted).toString();
	return res
}
/* 密码aes加密 */
function passwordEncrypt(text) {
	//获取加密内容的WordArray
	const contentBytes = CryptoJS.enc.Utf8.parse(text)
	//获取aes加密密钥的WordArray
	const keyBytes = CryptoJS.enc.Hex.parse(app_password_key())
	//获取iv的WordArray
	const ivBytes = CryptoJS.enc.Utf8.parse(app_password_iv())
	const encrypted = CryptoJS.AES.encrypt(contentBytes, keyBytes, {
		iv: ivBytes,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	})
	//aes加密结果base64
	const resBase64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64)
	return resBase64
}

//特殊16进制转-1
function hex2Byte(hexString) {
	hexString = hexString.toUpperCase();
	if (hexString == null || hexString.length == 0 || hexString.length % 2 != 0) {
		return null;
	}
	var data = new Int8Array(hexString.length / 2);
	var chars = hexString.split('');
	for (var i = 0; i < hexString.length; i += 2) {
		data[i / 2] = (toByte(chars[i]) << 4 | toByte(chars[i + 1]));
	}
	return data;
}
function toByte(c) {
	return "0123456789ABCDEF".indexOf(c)
}
//hex转字符串
function bytesToString(key) {
  var str = [];
  new Uint8Array(key.match(/[\da-f]{2}/gi)
    .map(function (h) { return parseInt(h, 16) }))
    .map(function (s) { str.push(String.fromCharCode(s)); });
  return str.join("");
}
//生产密码加解密密钥
function createPasswordKey(count = 32) {
	let key = CryptoJS.lib.WordArray.random(count / 2).toString().toUpperCase()
	return key
}
export default {
	encryptRSA,
	decryptRSA,
	networkEncrypt,
	networkDecrypt,
	passwordEncrypt,
}